package com.hx.springboot1.security;

import com.hx.springboot1.pojo.entity.TabRole;
import com.hx.springboot1.pojo.entity.TabUser;
import com.hx.springboot1.pojo.entity.TabUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private com.hx.springboot1.service.impl.RoleServiceImpl roleServiceImpl;
    @Autowired
    private com.hx.springboot1.service.impl.UserServiceImpl userServiceImpl;
    @Autowired
    private com.hx.springboot1.service.impl.UserRoleServiceImpl userRoleServiceImpl;

    @Override
    public UserDetails loadUserByUsername(String username) {
        Collection<GrantedAuthority> authorities  = new ArrayList<>();
        TabUser login = userServiceImpl.login(username);
        if (login==null){
            throw new UsernameNotFoundException("用户名不存在");
        }else if (login.getUserState()>0){
            throw new InternalAuthenticationServiceException("账户被禁用");
        }
        List<TabUserRole> TabUserRoles = userRoleServiceImpl.selectRolesById(login.getUserId());
        for (TabUserRole userRole: TabUserRoles){
            TabRole tabRole = roleServiceImpl.selectById(userRole.getRoleId());
            authorities.add(new SimpleGrantedAuthority(tabRole.getRoleName()));
        }
        return new User(login.getUsername(),new BCryptPasswordEncoder().encode(login.getPassword()),authorities);
    }
}
